package logic

import (
	"context"
	"errors"
	"user/models"
	"user/pkg"

	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	mobile, err := user.FindUserByMobile(in.Mobile)
	if err != nil {
		return nil, err
	}
	if mobile.ID == 0 {
		return nil, errors.New("当前用户不存在")
	}
	if mobile.Password != pkg.Md5Str(in.Password) {
		return nil, errors.New("密码错误请重新输入")
	}
	return &userrpc.LoginResponse{
		UserId: int64(mobile.ID),
	}, nil
}
